#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

using System.Web;

using System.Collections;
using WaveMaster.Holidays.Club.Domain;
using WaveMaster.Holidays.Club.Service;

#endregion

namespace WaveMaster.Holidays.Club.Web
{
    public partial class TripForm : Form
    {
        Trip m_trip;
        User m_current_user;
        EditMode m_editmode;
        TripService m_tripService;
        SeaPortService m_seaportService;
        VesselService m_vesselService;
        MainForm m_mainForm;
        UserControlManageTrip m_parentForm;

        public TripForm(string name, Trip user, User currentUser, MainForm mainForm, UserControlManageTrip parentForm, EditMode editmode)
        {
            InitializeComponent();
            m_tripService = (TripService)ServiceFactory.Instance().GetService(ServiceFactory.TRIP_SERVICE);
            m_seaportService = (SeaPortService)ServiceFactory.Instance().GetService(ServiceFactory.SEAPORT_SERVICE);
            m_vesselService = (VesselService)ServiceFactory.Instance().GetService(ServiceFactory.VESSEL_SERVICE);
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            
            initButtonEvent();
            initComboDataSource();
            if (user.m_tripID == 0)
            {
                clearForm();
            }
            else
            {
                m_trip = m_tripService.GetTripByID(user.m_tripID);
                loadTrip(); 
                enableForm(editmode == EditMode.Edit);
            }
            setEditMode(editmode);
            //enableForm(false);


           
        }

        private void clearForm()
        {
            textBoxUserCode.Text = string.Empty;
            comboBoxVessel.SelectedIndex = comboBoxVessel.Items.Count > 0 ? 0 : -1;
            comboBoxSeaPort.SelectedIndex = comboBoxSeaPort.Items.Count > 0 ? 0 : -1;
            //comboBoxDestinationPort.SelectedIndex = comboBoxDestinationPort.Items.Count > 0 ? 0 : -1;
            checkBoxAvailable.Checked = true;
            dateTimePickerDepDate.Value = DateTime.Today;
            comboBoxDepartureStatus.Text = DepartureStatus.Open.ToString();
            textBoxDate.Text = DateTime.Today.Day.ToString();
            textBoxMonth.Text = DateTime.Today.Month.ToString();
            textBoxYear.Text = DateTime.Today.Year.ToString();
            m_trip = new Trip();
            clearErrorProvider();
            enableForm(true);
            setEditMode(EditMode.Create);
            comboBoxVessel.Focus();
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }
              
        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            setEditMode(EditMode.Edit);
            enableForm(!toolBarButtonEdit.Enabled);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
            MessageBox.Show("Are you sure to cancel?", "Confirmation", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
             MessageBoxWindow msg = (MessageBoxWindow)sender;
             if (msg.DialogResult == DialogResult.Yes)
             {
                 this.Close();
             }
        }
        private void initComboDataSource()
        {
            comboBoxSeaPort.DataSource = m_seaportService.LoadAllSeaPort();
            //comboBoxDestinationPort.DataSource = m_seaportService.LoadAllSeaPort();
            comboBoxVessel.DataSource = m_vesselService.LoadAllVessel();
            comboBoxDepartureStatus.DataSource = Enum.GetNames(typeof(DepartureStatus));
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadTrip();
        }

        private void clearErrorProvider()
        {
            errorProviderUser.SetError(textBoxUserCode, "");
            errorProviderUser.SetError(comboBoxSeaPort, "");
            errorProviderUser.SetError(comboBoxDestinationPort, "");
            errorProviderUser.SetError(comboBoxVessel, "");
        }
        private bool isValidForm()
        {
            clearErrorProvider();
            bool valid_a = textBoxUserCode.Text != string.Empty;
            bool valid_b = comboBoxSeaPort.SelectedValue != null;
            bool valid_d = comboBoxDestinationPort.SelectedValue != null;
            bool valid_c = comboBoxVessel.SelectedValue != null;
            bool valid_e = comboBoxSeaPort.Text != comboBoxDestinationPort.Text;
            bool valid_f = validMaskTextBox();
            if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "User Code can not be empty");
            if (!valid_b) errorProviderUser.SetError(comboBoxSeaPort, "Sea Port can not be empty");
            if (!valid_c) errorProviderUser.SetError(comboBoxVessel, "Sea Port can not be empty");
            if (!valid_d) errorProviderUser.SetError(comboBoxDestinationPort, "Destination Sea Port can not be empty");
            if (!valid_e) errorProviderUser.SetError(comboBoxDestinationPort, "Destination Sea Port can not same as departure Port");
            if (!valid_f) errorProviderUser.SetError(maskedTextBoxDepartureTime    , "Not valid time");
            return valid_a && valid_b && valid_c && valid_d && valid_e && valid_f;
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_trip.m_tripCode = textBoxUserCode.Text;
                    m_trip.m_vessel = (Vessel)comboBoxVessel.SelectedItem;
                    m_trip.m_seaPort = (SeaPort)comboBoxSeaPort.SelectedItem;
                    m_trip.m_departureDate = dateTimePickerDepDate.Value;
                    m_trip.m_departureTime = maskTextBoxDate();// m_trip.m_departureDate.AddHours(dateTimePickerDepTime.Value.Hour).AddMinutes(dateTimePickerDepTime.Value.Minute);
                    m_trip.m_avaliable = checkBoxAvailable.Checked;
                    m_trip.m_destinationPortID = (SeaPort)comboBoxDestinationPort.SelectedItem;
                    m_trip.m_departureStatus = (DepartureStatus)Enum.Parse(typeof(DepartureStatus), comboBoxDepartureStatus.Text);
                    if (m_trip.m_tripID > 0)
                    {
                        m_trip.m_modfctnBy = m_current_user.UserID;
                        m_tripService.UpdateTrip(m_trip);
                    }
                    else
                    {
                        m_trip.m_cretnBy = m_current_user.UserID;
                        m_tripService.InserTrip(m_trip);
                    }
                    m_parentForm.LoadAllTrip();
                  //  MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("Record has been saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                   // this.Close();
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }

        void closeForm(object sender, EventArgs e)
        {
            this.Close();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete)&& m_current_user.RoleDetails(this.Name).NewFlag;

            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.RoleDetails(this.Name).UpdateFlag;
            buttonSave.Enabled = toolBarButtonSave.Enabled;
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        private void enableForm(bool enable)
        {
            textBoxUserCode.ReadOnly = !enable;
            comboBoxVessel.Enabled = enable;
            comboBoxSeaPort.Enabled = enable;
            dateTimePickerDepDate.Enabled = enable;
            checkBoxAvailable.Enabled = enable;
            comboBoxDestinationPort.Enabled = enable;
            comboBoxDepartureStatus.Enabled = enable;
            textBoxDate.Enabled = enable;
            textBoxMonth.Enabled = enable;
            textBoxYear.Enabled = enable;
            maskedTextBoxDepartureTime.Enabled = enable;
        }

        private void loadTrip()
        {
            m_trip.m_vessel = m_vesselService.GetVesselByID(m_trip.m_vessel.m_vesselID);
            m_trip.m_seaPort = m_seaportService.GetSeaPortByID(m_trip.m_seaPort.m_seaPortID);
            m_trip.m_destinationPortID = m_seaportService.GetSeaPortByID(m_trip.m_destinationPortID.m_seaPortID);

            textBoxUserCode.Text = m_trip.m_tripCode;
            comboBoxVessel.Text = m_trip.m_vessel.ToString();
            comboBoxSeaPort.Text = m_trip.m_seaPort.ToString();
            dateTimePickerDepDate.Value = m_trip.m_departureDate;
            textBoxDate.Text = dateTimePickerDepDate.Value.Day.ToString();
            textBoxMonth.Text = dateTimePickerDepDate.Value.Month.ToString();
            textBoxYear.Text = dateTimePickerDepDate.Value.Year.ToString();
            maskedTextBoxDepartureTime.Text = m_trip.m_departureTime.Hour.ToString().PadLeft(2, '0') + ":" + m_trip.m_departureTime.Minute.ToString().PadLeft(2, '0');
            checkBoxAvailable.Checked = m_trip.m_avaliable;
            comboBoxDestinationPort.Text = m_trip.m_destinationPortID.ToString();
            comboBoxDepartureStatus.Text = m_trip.m_departureStatus.ToString();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void comboBoxSeaPort_SelectedIndexChangedQueued(object sender, EventArgs e)
        {

        }

        private void TriptForm_Load(object sender, EventArgs e)
        {
            KeyEnterEventFire(this.groupBox1.Controls);
            comboBoxVessel.Focus();
        }

        private void KeyEnterEventFire(Control.ControlCollection controls)
        {
            foreach (Control c in controls)
            {
                if (c is TextBox || c is ComboBox || c is DateTimePicker || c is Button || c is CheckBox)
                {
                    c.KeyPress += new KeyPressEventHandler(c_KeyPress);
                }
                KeyEnterEventFire(c.Controls);
            }
        }

        void c_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                Control cont = (Control)sender;
                this.SelectNextControl((Control)sender, true, true, true, true);
            }
        }

        private void comboBoxSeaPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            IList ds = m_seaportService.LoadAllSeaPort();
            foreach (SeaPort sp in ds)
            {
                if (sp.ToString() == comboBoxSeaPort.Text)
                {
                    ds.Remove(sp);
                    break;
                }
            }
            comboBoxDestinationPort.DataSource = ds;
        }

        private void textBoxYear_Validating(object sender, CancelEventArgs e)
        {
            bool valid = false;
            TextBox tb = (TextBox)sender;
            try
            {
                int d = Convert.ToInt16(tb.Text);
                DateTime date = new DateTime(Convert.ToInt16(textBoxYear.Text), Convert.ToInt16(textBoxMonth.Text), Convert.ToInt16(textBoxDate.Text));
                dateTimePickerDepDate.Value = date;
                valid = true;
            }
            catch { }
            e.Cancel = !valid;
        }

        private void textBoxDate_GotFocus(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            tb.SelectAll();
        }

        private bool validMaskTextBox()
        {
            bool valid = false;
            string time = maskedTextBoxDepartureTime.Text;
            string[] times = time.Split(':');
            int hh = Convert.ToInt16(times[0]);
            int mm = Convert.ToInt16(times[1]);
            valid = (hh > 0 && hh <= 24) && (mm >= 0 && mm <= 60);
            return valid;
        }
        private DateTime maskTextBoxDate()
        {
            string time = maskedTextBoxDepartureTime.Text;
            string[] times = time.Split(':');
            int hh = Convert.ToInt16(times[0]);
            int mm = Convert.ToInt16(times[1]);
            return m_trip.m_departureDate.AddHours(hh).AddMinutes(mm);
        }


        private void dateTimePickerDepDate_ValueChanged(object sender, EventArgs e)
        {
            textBoxDate.Text = dateTimePickerDepDate.Value.Day.ToString();
            textBoxMonth.Text = dateTimePickerDepDate.Value.Month.ToString();
            textBoxYear.Text = dateTimePickerDepDate.Value.Year.ToString();
        }
    }
}